import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getUserInfo, getUserDetailById } from '@/api/user'
const state = () => ({
  token: getToken() || null,
  userInfo: {}
})

const mutations = {
  // 设置token
  setToken(state, token) {
    state.token = token
    // 本地存储token
    setToken(token)
  },
  // 移除token
  removeToken(state) {
    state.token = null
    // 本地移除token
    removeToken()
  },
  // 设置用户信息
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  // 移除用户信息
  removeUserInfo(state) {
    state.userInfo = {}
  }
}

const actions = {
  // 登录获取token,给vuex进行token赋值
  async userLogin(store, userObj) {
    const res = await login(userObj)
    store.commit('setToken', res.data)
  },
  // 调用接口获取用户信息
  async getUserInfo(store) {
    const res = await getUserInfo()
    // console.log(res)
    const resp = await getUserDetailById(res.data.userId)
    // console.log(resp)
    store.commit('setUserInfo', { ...res.data, ...resp.data })
  },
  // 退出登录删除本地token和信息
  userLogout(store) {
    store.commit('removeToken')
    store.commit('removeUserInfo')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

